from Crypto.Cipher import AES
from binascii import b2a_hex,a2b_hex  
import base64
import os


def the_str16(st): #补16位
    st=zwencode(st)
    while len(st)%16!=0:
        st=st+'\0'
    return str.encode(st)

def zwencode(st): #编码
    st=base64.b64encode(st.encode('utf-8'))
    st=st.decode()
    return st

def zwdecode(st): #解码
    missing_padding = 4 - len(st) % 4
    if missing_padding:
        st += '='* missing_padding
    #st=st.encode()
    st=base64.b64decode(st)
    st=st.decode('utf-8')
    return st



def encryt_ecb(key,st): #加密
    st=the_str16(st)
    key=the_str16(key)
    aes=AES.new(key,AES.MODE_ECB)
    text_str=aes.encrypt(st)
    return b2a_hex(text_str)

def decryt_ecb(key,st): #解密
    key=the_str16(key)
    aes=AES.new(key,AES.MODE_ECB)
    text_str=aes.decrypt(a2b_hex(st))
    return text_str
        
if __name__=='__main__':
    isjiami=input('输入encode加密，decode解密：')
    if isjiami == 'encode':
        text=input('输入要加密字符：')
        key=input('输入key:')
        try:
            print(encryt_ecb(key,text).decode())
            if not os.path.exists('d:/zhjilu/'):
                os.mkdir('d:/zhjilu/')
            with open('d:/zhjilu/encodefile.txt','a') as f:
                f.write(encryt_ecb(key,text).decode()+'\n\n')
       
        except:
            print('加密失败')       
        
    if isjiami == 'decode':
        key=input('输入key:')
        try:
            with open('d:/zhjilu/encodefile.txt','r') as f:
                encodstr=f.read()
                for encodst in encodstr.split():
                    try:
                        print(zwdecode(decryt_ecb(key,encodst).decode()))
                    except:
                        print('解密失败')
        except:
            print('没有记录')
                

